import os

def execute(code_str):
    code = code_str
    write_data(code)
    create_file("test.py", "output.py")
    #print "code output:", code
    list_date = []
    list_data = []
    list_data_tmp = []
    a = os.popen('python ./new_sim.py')
    line = a.readline()

    str_line = str(line).strip('[|]')
    list_data_tmp = str_line.split(',')

    for i in range(len(list_data_tmp)-1):
        list_data.append(float(list_data_tmp[i]))

    length = len(list_data)
    list_date = range(length)

    return list_date, list_data

def write_data(data):
    output_file = open('output.py', 'wb')
    output_file.write(data)
    output_file.close()

def create_file(file1, file2):
    file_origin = open(file1, "r")
    content = file_origin.read()
    content_add = ""
    pos = content.find("#insert above")

    #if the code is not written in the file 'file2', then pass.
    if os.path.getsize(file2) == 0:
        content = content[:pos] + "    pass\n" + content[pos:]
    else:
        file_add = open(file2, "r")
        while 1:
            line = file_add.readline()
            if not line:
                break
            new_line = "    " + line.rstrip() + '\n'
            content_add = content_add + new_line
        content = content[:pos] + content_add + content[pos:]
        file_add.close()

    file_origin = open("./new_sim.py", "w")
    file_origin.write(content)
    file_origin.close()
